import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.data.success) {
      // 操作成功
      return response.data
    } else {
      // 如果success为false 业务出错,直接触发reject
      // 被catch分支捕获
      return Promise.reject(new Error(response.data.message))
    }
  },
  error => {
    // 响应回来 如果token报错
    if (error.response.data.code === 10002) {
      // 清除信息
      store.dispatch('user/userLoginout')
      // 跳转登录页面 后面添加登录未遂地址//  .js -- router.currentRoute.fullPath
      window.alert('登录已过期，请重新登录')
      router.push({ path: '/login?return_url=' + encodeURIComponent(router.currentRoute.fullPath) })
    }
    return Promise.reject(error) // 返回执行错误 让当前的执行链跳出成功 直接进入 catch
  }
)
// 请求拦截器store.state.user.token
service.interceptors.request.use(
  function(config) {
    if (store.state.user.token) {
      config.headers['Authorization'] = `Bearer ${store.state.user.token}`
    }
    return config
  },
  function(error) {
    return Promise.reject(error)
  }
)
export default service
